package com.elinkway.infinitemovies.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.elinkway.infinitemovies.adapter.AlbumShowAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.RequestFeedMoreTask;
import com.elinkway.infinitemovies.async.RequestHomePageTask;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.bean.AlbumShowBean;
import com.elinkway.infinitemovies.bean.HomePageList;
import com.elinkway.infinitemovies.bean.IntervalBean;
import com.elinkway.infinitemovies.bean.MainHeaderBean;
import com.elinkway.infinitemovies.bean.NewAdDataBean;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.dao.ChannelContentDao;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.requesttask.RequestAdTask;
import com.elinkway.infinitemovies.selfdata.AdRequestStatis;
import com.elinkway.infinitemovies.selfdata.SelfDataConstant;
import com.elinkway.infinitemovies.selfdata.bean.LaunchDurationDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.ui.activity.NewMainActivity;
import com.elinkway.infinitemovies.ui.activity.SplashActivity;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.BaseRecyclerFragment;
import com.elinkway.infinitemovies.view.DiffCallBack;
import com.elinkway.infinitemovies.view.PublicLoadLayout;
import com.elinkway.infinitemovies.widget.MyGridLayoutManager;
import com.handmark.pulltorefresh.library.BDReporter;
import com.recyclerlayout.refresh.MyMessageEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhaopeipei on 2017/3/10.
 */
public class HomeTestFragment extends BaseRecyclerFragment implements BDReporter {

    public static final String TAG = "HomeTestFragment";
    public static final String DEFAULT_PAGE = "default_page";

    private RequestHomePageTask homePageTask;
    private RequestFeedMoreTask moreFeedTask;
    private RequestFeedMoreTask pulldownFeedTask;
    private MyGridLayoutManager mGridLayoutManager;
    private AlbumShowAdapter mAdapter;
    private String unlimitFeedId = "";
    private String unlimitFeedVt = "";
    private String pullToMoreFeedId = "";
    private String pullToMoreFeedVt = "";
    private ArrayList mAllItemList;
    private NewAdDataBean mFocusBannerAdData;
    private NewAdDataBean mHomeBannerAdData;
    private String defaultPage = "page_index";
    private MainHeaderBean mHeaderBean;
    private String mBDPageIndex;
    private Map<String, String> mRecDataReportTags;
    private int mScrollY = 0;
    private HomePageList mHomePageList;
    private String mDefaultPage = ""; // 默认展示的频道page
    private LaunchDurationDataRecord launchDuration; // 启动时长日志
    private View mFragmentView;
    private String oldPageJson = "";
    private ChannelContentDao mDao;
    private boolean isNeedRequestAd = true; // 是否要请求广告

    private static final int ONE_COLUMN = 6;
    private static final int TWO_COLUMN = 357;
    private static final int THREE_COLUMN = 236;
    private static final int ALL_COLUMN = 720;

    private ItemInteractionListener itemInteractionListener;

    private boolean isCurPage = true;

    private boolean isReported = false;

    private static final String PULL_UP = "pull_up";
    private static final String PULL_DOWN = "pull_down";
    private int mHomeBannerAdIndex = 0;

    public String getmBDPageIndex() {
        return mBDPageIndex;
    }

    public void setmBDPageIndex(String mBDPageIndex) {
        this.mBDPageIndex = mBDPageIndex;
    }

    public Map<String, String> getmRecDataReportTags() {
        return mRecDataReportTags;
    }

    public void setmRecDataReportTags(Map<String, String> mRecDataReportTags) {
        this.mRecDataReportTags = mRecDataReportTags;
    }

    public int getmScrollY() {
        return mScrollY;
    }

    public void setmScrollY(int mScrollY) {
        this.mScrollY = mScrollY;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mHeaderBean = (MainHeaderBean) bundle.getSerializable("headerbean");
            mDefaultPage = bundle.getString(DEFAULT_PAGE);
            if (mHeaderBean != null && mHeaderBean.getPage().equals(mDefaultPage)) {
                launchDuration = (LaunchDurationDataRecord)bundle.getSerializable(SplashActivity.LAUNCHLOG);
            }
        }
        mBDPageIndex = "home_" + mHeaderBean.getPage();
        mDao = new ChannelContentDao(getContext());
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        itemInteractionListener = new ItemInteractionListener();
        setPullListener(itemInteractionListener);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (mFragmentView == null) {
            mFragmentView = super.onCreateView(inflater, container, savedInstanceState);
            if (NetWorkTypeUtils.isNetAvailable()) {
                // 请求过网络数据
                if (SharePreferenceManager.getVaule(getContext(), mHeaderBean.getPage())) {
                    mHomePageList = getHomePageListByPage(mHeaderBean.getPage());
                    if (mHomePageList != null && mHomePageList.getPageItemList() != null) {
                        isNeedRequestAd = false;
                        setChannelContent(mHomePageList);
                        root.finish();
                    }
                } else {
                    // 没有请求过网络数据
                    if (isCurPage) {
                        // 先加载缓存
                        mHomePageList = getHomePageListByPage(mHeaderBean.getPage());
                        if (mHomePageList != null && mHomePageList.getPageItemList() != null) {
                            isNeedRequestAd = false;
                            setChannelContent(mHomePageList);
                            root.finish();
                        }
                    }
                    requestMianData(false);
                }
            } else {
                // 无网络
                mHomePageList = getHomePageListByPage(mHeaderBean.getPage());
                if (mHomePageList != null && mHomePageList.getPageItemList() != null) {
                    isNeedRequestAd = false;
                    setChannelContent(mHomePageList);
                    root.finish();
                } else {
                    root.error(false, false);
                    root.setmRefreshData(new PublicLoadLayout.RefreshData() {
                        @Override
                        public void refreshData() {
                            root.loading(false);
                            requestRefresh();
                        }
                    });
                }
            }
        } else {
            addOnScrollListener();
        }
        return mFragmentView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != mFragmentView) {
            ((ViewGroup) mFragmentView.getParent()).removeView(mFragmentView);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        String currentBottomTab = "home";
        if (getActivity() instanceof NewMainActivity) {
            currentBottomTab = ((NewMainActivity) getActivity()).getmCurrentBottomTab();
        }

        if (isCurPage && "home".equals(currentBottomTab)) {
            if (!isReported) {
                if (getActivity() instanceof NewMainActivity) {
                    ((NewMainActivity) getActivity()).setCurrentPageId(mBDPageIndex);
                }
                BigDataApi.bigDataPageShowReport(mBDPageIndex, new HashMap<String, String>(), getActivity());
                resetInscreenData();
                bigdataReportShow();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isReported = false;
    }

    public static HomeTestFragment newInstance(MainHeaderBean bean,String defaultPage,LaunchDurationDataRecord launchRecord) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("headerbean", bean);
        bundle.putString(HomeTestFragment.DEFAULT_PAGE,defaultPage);
        bundle.putSerializable(SplashActivity.LAUNCHLOG,launchRecord);
        HomeTestFragment contentFragment = new HomeTestFragment();
        contentFragment.setArguments(bundle);
        return contentFragment;
    }

    public void setChannelContent(HomePageList result) {
        if (result != null && result.getPageItemList() != null) {
            setData(result.getPageItemList());
            mHomeBannerAdIndex = result.getHomeBannerAdIndex();
            if (!TextUtils.isEmpty(result.getUnlimitFeedId())) {
                unlimitFeedId = result.getUnlimitFeedId();
                unlimitFeedVt = result.getUnlimitFeedVt();
                mOverScrollView.setOverScrollEnable(false);
            } else {
                unlimitFeedId = "";
                mOverScrollView.setOverScrollEnable(true);
            }
            if(!TextUtils.isEmpty(result.getPullToMoreFeedId())){
                pullToMoreFeedId = result.getPullToMoreFeedId();
                pullToMoreFeedVt = result.getPullToMoreFeedVt();
            }else{
                pullToMoreFeedId = "";
            }
            if (mHeaderBean != null && MoviesApplication.getInstance().isFirstEnterApplication) {
                MoviesApplication.getInstance().isFirstEnterApplication = false;
                if (getParentFragment() != null && getParentFragment() instanceof NewHomeFragment) {
                    ((NewHomeFragment) getParentFragment()).showHistory();
                }
            }
        }
    }

    class HomePageRequestListener extends BasePullRequestListener<HomePageList> {
        private boolean isRefresh = false;

        public HomePageRequestListener (boolean isRefresh) {
            this.isRefresh = isRefresh;
        }

        @Override
        public boolean onRequestFailed() {
            super.onRequestFailed();
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, HomePageList result) {
            super.onRequestSuccess(updateId, result);
            if (mHeaderBean != null) {
                SharePreferenceManager.saveVaule(getContext(),mHeaderBean.getPage(),true);
            }
            if (launchDuration != null) {
                launchDuration.setRequestPageSucc(System.currentTimeMillis()+"");
            }
            if (result == null) {
                return;
            }
            if (!TextUtils.isEmpty(oldPageJson) && !isRefresh) {
                String newPageJson = "";
                if (mDao != null) {
                    newPageJson = mDao.getJsonByPage(mHeaderBean.getPage());
                }
                if (oldPageJson.equals(newPageJson)) {
                    //刷新时重置广告
                    mFocusBannerAdData = null;
                    mHomeBannerAdData = null;
                    requestFocusBannerAdData();
                    requestHomeBannerAdData();
                    return;
                }
            }
            isNeedRequestAd = true;
            mHomePageList = result;
            setChannelContent(result);
        }

        @Override
        public void onPreRequest() {

        }
    }

    class FeedMoreRequestListener extends BasePullRequestListener<HomePageList> {

        String requestType;

        public FeedMoreRequestListener(String type) {
            requestType = type;
        }

        @Override
        public boolean onRequestFailed() {
            Log.i(TAG, "requestMore  onRequestFailed");
//            super.onRequestFailed();
            if (itemInteractionListener != null) {
                itemInteractionListener.requestComplete();
            }
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, HomePageList result) {
            Log.i(TAG, "requestMore  onRequestSuccess");
            if (result != null && result.getPageItemList() != null) {
                if (PULL_DOWN.equals(requestType)) {
                    setMoreData(result.getPageItemList(), PULL_DOWN);
                } else {
                    setMoreData(result.getPageItemList(), PULL_UP);
                }
            }
            super.onRequestSuccess(updateId, result);
        }

        @Override
        public void onPreRequest() {

        }
    }

    public void setMoreData(ArrayList moreData, String type) {
        if (PULL_DOWN.equals(type)) {
            mAllItemList.addAll(0, moreData);
        } else {
            mAllItemList.addAll(moreData);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            MoviesApplication.getInstance().setLastPageClassName(TAG);
            isCurPage = true;
            isReported = true;
            BigDataApi.bigDataPageShowReport(mBDPageIndex, new HashMap<String, String>(), getActivity());
            resetInscreenData();
            bigdataReportShow();
        } else {
            isCurPage = false;
        }
    }

    private HomePageList getHomePageListByPage(String page) {
        HomePageList list = null;
        if (mDao != null) {
            oldPageJson = mDao.getJsonByPage(page);
            list = mDao.getContentByPage(page,oldPageJson);
        }
        return list;
    }

    private void setData(ArrayList itemlist) {
        if (itemlist.size() > 0) {
            ArrayList oldlist = new ArrayList();
            mGridLayoutManager = new MyGridLayoutManager(getActivity(), ALL_COLUMN);
            if (mAllItemList == null) {
                mAllItemList = new ArrayList();
            } else {
                oldlist.addAll(mAllItemList);
                mAllItemList.clear();
            }
            mAllItemList.addAll(itemlist);
            mFocusBannerAdData = null;  //刷新时重置广告
            mHomeBannerAdData = null;

            if(mAdapter == null){
                mAdapter = new AlbumShowAdapter(getActivity(), mAllItemList, mBDPageIndex);
                mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        Object obj = mAdapter.getItem(position);
                        if (obj instanceof AlbumShowBean) {
                            AlbumShowBean bean = (AlbumShowBean) obj;
                            if (MoviesConstant.MODEL_HALF == bean.getType()) {
                                return TWO_COLUMN;
                            } else if (MoviesConstant.MODEL_THIRD == bean.getType()) {
                                return THREE_COLUMN;
                            } else {
                                return ALL_COLUMN;
                            }
                        } else if (obj instanceof IntervalBean) {
                            return ONE_COLUMN;
                        } else {
                            return ALL_COLUMN;
                        }
                    }
                });
                setLayoutManager(mGridLayoutManager);
                setAdapter(mAdapter);
            }else{
                DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffCallBack(oldlist, itemlist), true);
                diffResult.dispatchUpdatesTo(mAdapter);
                mAdapter.setDatas(mAllItemList);
                if(mAdapter.getItem(0) instanceof List){
                    mAdapter.setRefresh(true);
                    mAdapter.notifyItemChanged(0);
                }
                mAdapter.setNeedResetBannerAd(true);
            }
            if (isNeedRequestAd) {
                requestFocusBannerAdData();
                requestHomeBannerAdData();
            }
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    switch (newState) {
                        case RecyclerView.SCROLL_STATE_IDLE:
                            bigdataReportShow();
                            break;
                    }
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                }
            });
            if (launchDuration != null) {
                launchDuration.setShowIndexPage(System.currentTimeMillis()+"");
                RealmDaoManager.addMyDataRecord(launchDuration);
                launchDuration = null;
            }
        }
    }

    public void resetInscreenData() {
        if (mAdapter != null) {
            for (int i = 0; i < mAdapter.getItemCount(); i++) {
                Object obj = mAdapter.getItem(i);
                if (obj instanceof AlbumShowBean) {
                    ((AlbumShowBean) (mAdapter.getItem(i))).setInScreen(false);
                }
            }
        }
    }

    public void bigdataReportShow() {
        if (mAdapter == null || mGridLayoutManager == null) {
            return;
        }
        int firstItemPosition = mGridLayoutManager.findFirstVisibleItemPosition();
        int lastItemPosition = mGridLayoutManager.findLastVisibleItemPosition();
        for (int i = 0; i < mAdapter.getItemCount(); i++) {
            Object obj = mAdapter.getItem(i);
            if (obj instanceof AlbumShowBean) {
                if (i >= firstItemPosition && i <= lastItemPosition) {
                    AlbumShowBean bean = (AlbumShowBean) obj;
                    if (!bean.isInScreen()) {
                        String display = bean.getDisplay();
                        if (Utils.ALBUM.equals(display)) {
                            Map<String, String> dataMap = BigDataApi.createDataMap(BigDataConstants.ACODE_EXPOSURE, "recnum=" + bean.getRecname(), "0", "-", bean.getAid(), "-");
                            dataMap.put("rank", ((AlbumShowBean) obj).getCurrentShowIndex() + 1 + "");
                            dataMap.put("cur_url", mBDPageIndex);
                            dataMap.put("reid", ((AlbumShowBean) obj).getReid());
                            dataMap.put("bucket", ((AlbumShowBean) obj).getBucket());
                            BigDataApi.bigDataCommonReport(dataMap, getActivity());
                        } else if (Utils.LINK.equals(display)) {
                            Map<String, String> dataMap = BigDataApi.createDataMap(BigDataConstants.ACODE_EXPOSURE, "recnum=" + bean.getRecname(), "0", "-", "", "");
                            dataMap.put("rank", ((AlbumShowBean) obj).getCurrentShowIndex() + 1 + "");
                            dataMap.put("cur_url", mBDPageIndex);
                            BigDataApi.bigDataCommonReport(dataMap, getActivity());
                        } else if (Utils.THEME.equals(display)) {
                            Map<String, String> dataMap = BigDataApi.createDataMap(BigDataConstants.ACODE_EXPOSURE, "recnum=" + bean.getRecname(), "0", "-", "", bean.getThemeid());
                            dataMap.put("rank", ((AlbumShowBean) obj).getCurrentShowIndex() + 1 + "");
                            dataMap.put("cur_url", mBDPageIndex);
                            BigDataApi.bigDataCommonReport(dataMap, getActivity());
                        }
                        ((AlbumShowBean) (mAdapter.getItem(i))).setInScreen(true);
                    }
                } else {
                    ((AlbumShowBean) (mAdapter.getItem(i))).setInScreen(false);
                }
            }
        }
    }

    private class ItemInteractionListener extends PullListener {
        @Override
        public void requestMore() {
            super.requestMore();
            if (!TextUtils.isEmpty(unlimitFeedId)) {
                //加载更多feed流数据
                moreFeedTask = new RequestFeedMoreTask(MoviesApplication.getInstance(), unlimitFeedId, unlimitFeedVt);
                moreFeedTask.setListener(new FeedMoreRequestListener(PULL_UP));
                moreFeedTask.start();
            } else {
                resetLoading();
            }
        }

        @Override
        public void requestRefresh() {
            super.requestRefresh();
            if (TextUtils.isEmpty(pullToMoreFeedId) || mAllItemList == null) {
                EventBus.getDefault().post(new MyMessageEvent(2));
                requestMianData(true);
            } else {
                requestPullDownFeedData();
            }
        }

        @Override
        public void requestFailure() {
            super.requestFailure();
        }

        @Override
        public void requestComplete() {
            super.requestComplete();
        }

        @Override
        protected boolean hasMore() {
            return super.hasMore();
        }
    }

    private void requestMianData(boolean isRefresh) {
        if (null != homePageTask && !homePageTask.isCancelled()) {
            homePageTask.cancel();
            homePageTask = null;
        }
        homePageTask = new RequestHomePageTask(MoviesApplication.getInstance(), mHeaderBean.getPage());
        homePageTask.setListener(new HomePageRequestListener(isRefresh));
        homePageTask.start();
        if (launchDuration != null) {
            launchDuration.setRequestPagePort(System.currentTimeMillis()+"");
        }
    }

    private void requestPullDownFeedData() {
        if (null != pulldownFeedTask && !pulldownFeedTask.isCancelled()) {
            pulldownFeedTask.cancel();
            pulldownFeedTask = null;
        }
        pulldownFeedTask = new RequestFeedMoreTask(MoviesApplication.getInstance(), pullToMoreFeedId, pullToMoreFeedVt);
        pulldownFeedTask.setListener(new FeedMoreRequestListener(PULL_DOWN));
        pulldownFeedTask.start();
    }

    private void requestFocusBannerAdData() {
        if (!defaultPage.equals(mHeaderBean.getPage())) {
            return;
        }
        if (mFocusBannerAdData == null) {
            new RequestAdTask(MoviesApplication
                    .getInstance(), MoviesHttpApi.FOCUS_BANNER, new FocusBannerAdRequestResultListener()).start();
        } else {
            addFocusBannerAdData();
        }
    }

    private class FocusBannerAdRequestResultListener implements
            RequestResultListener<NewAdDataBean> {

        @Override
        public boolean onRequestFailed() {
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, NewAdDataBean result) {
            if (result != null) {
                AdRequestStatis.selfResponseReport(result, SelfDataConstant.AD_PO_FOCUS);
                mFocusBannerAdData = result;
                addFocusBannerAdData();
            }
        }

        @Override
        public void onPreRequest() {

        }
    }

    private void addFocusBannerAdData() {
        boolean isChanged = false;
        int changeIndex = 0;
        if (mAllItemList != null && mAllItemList.size() > 0) {
            if(mFocusBannerAdData == null){
                return;
            }
            for (int i = 0; i < mAllItemList.size(); i++) {
                /**
                 * 首页轮播banner的广告
                 */
                if (mAllItemList.get(i) instanceof ArrayList) {
                    int adPosition = 2;
                    if (!TextUtils.isEmpty(mFocusBannerAdData.ext.focusIndex)) {
                        adPosition = Integer.valueOf(mFocusBannerAdData.ext.focusIndex) - 1;
                    }
                    if (adPosition >= 0 && adPosition < ((ArrayList) mAllItemList.get(i)).size()) {
                        ((ArrayList) mAllItemList.get(i)).add(adPosition, mFocusBannerAdData);
                        isChanged = true;
                        changeIndex = i;
                    }
                }
            }
            if (isChanged) {
                mAdapter.setRefresh(true);
                mAdapter.notifyItemChanged(changeIndex);
                new android.os.Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(mFocusBannerAdData != null){
                            mFocusBannerAdData.isShow = true;
                        }
                    }
                }, 1000);
            }
        }
    }

    private void requestHomeBannerAdData() {
        if (!defaultPage.equals(mHeaderBean.getPage())) {
            return;
        }
        if (mHomeBannerAdData == null) {
            new RequestAdTask(MoviesApplication
                    .getInstance(), MoviesHttpApi.HOME_BANNER, new HomeBannerAdRequestResultListener()).start();
        } else {
            addHomeBannerAdData();
        }
    }

    private class HomeBannerAdRequestResultListener implements
            RequestResultListener<NewAdDataBean> {

        @Override
        public boolean onRequestFailed() {
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, NewAdDataBean result) {
            if (result != null) {
                AdRequestStatis.selfResponseReport(result, SelfDataConstant.AD_PO_HOMEBANNER);
                mHomeBannerAdData = result;
                addHomeBannerAdData();
            }
        }

        @Override
        public void onPreRequest() {

        }
    }

    private void addHomeBannerAdData() {
        if (mAllItemList != null && mAllItemList.size() > 0) {
            if(mHomeBannerAdData == null){
                return;
            }
            if(mHomeBannerAdIndex > 0){
                mAllItemList.add(mHomeBannerAdIndex, mHomeBannerAdData);
                mAdapter.notifyItemInserted(mHomeBannerAdIndex);
            }
        }
    }

    @Override
    public void bigDateShowReport(int y) {

    }
}
